﻿using System;
using System.Reflection;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.ApplicationPages;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using ipi.MCC.Controls;
using ipi.MCC.Global;

namespace ipi.MCC.Pages
{
    public class MCCAdministrationPage : Microsoft.SharePoint.WebControls.LayoutsPageBase
    {
        protected MCCTreeSitesControl sscCurrentWeb;
        protected MCCTreeEditControl dtNavigate;
        protected MCCTreeAdminControl nhTreeNav;
        protected Button btnClearCache;
        protected Panel pnlMasterWeb;
        protected Panel pnlTree;
        protected Panel pnlSitesTree;
        protected Panel pnlTreeNav;
        protected Label lblMasterWeb;
        protected TextBox txtMasterWeb;
        protected Button btnMasterWeb;
        protected Button btnCancel;
        protected CustomValidator validGlobal;
        protected CustomValidator validMasterWeb;

        protected EncodedLiteral elPageTitle;
        protected EncodedLiteral elDescription;
        
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {

                dtNavigate.OnNodeSelected += new OnNodeSelectedHandler(TreeNodeSelected);
                nhTreeNav.OnNavigationSelected += new OnNavigationSelectedHandler(NaviNodeSelected);
                nhTreeNav.OnTreeChanged += new OnTreeChangedHandler(TreeStructureChanged);
                btnClearCache.Click += new EventHandler(btnClearCache_Click);
                btnMasterWeb.Click += new EventHandler(btnMasterWeb_Click);

                if (!Page.IsPostBack)
                {
                    sscCurrentWeb.SelectAction = TreeNodeSelectAction.Expand;
                    sscCurrentWeb.ShowCheckBoxes = TreeNodeTypes.Leaf;
                    
                    btnClearCache.Text = Resources.Resources.MCCAdministrationPage_btnClearCache;
                    lblMasterWeb.Text = Resources.Resources.MCCAdministrationPage_lblMasterWeb;
                    btnMasterWeb.Text = Resources.Resources.MCCAdministrationPage_btnMasterWeb;

                    elPageTitle.Text = Resources.Resources.AdminPage_Title;
//                    elDescription.Text = Resources.Resources.AdminPage_Description;

                    ipi.MCC.Global.WebSettings wsMain = new ipi.MCC.Global.WebSettings(SPContext.Current.Site.RootWeb);
                    string sMasterWebURL = wsMain.MasterWebURL;
                    if (!string.IsNullOrEmpty(sMasterWebURL) || (wsMain.IsReferenceSet))
                    {
                        pnlSitesTree.Visible = true;
                        pnlMasterWeb.Visible = false;
                        pnlTree.Visible = string.IsNullOrEmpty(sMasterWebURL);
                        pnlTreeNav.Visible = string.IsNullOrEmpty(sMasterWebURL);
                        txtMasterWeb.Text = sMasterWebURL;
                    }
                    else
                    {
                        pnlSitesTree.Visible = false;
                        pnlMasterWeb.Visible = true;
                        pnlTree.Visible = true;
                        pnlTreeNav.Visible = true;
                    }

                    sscCurrentWeb.CheckedItems = wsMain.SitesToSearch;
                }
            }
            catch (Exception exc)
            {
                validGlobal.ErrorMessage = Exceptions.HandleException(exc, this.GetType(), MethodBase.GetCurrentMethod(), LoggingType.Exception);
                validGlobal.IsValid = false;
            }
        }

        protected void btnMasterWeb_Click(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(txtMasterWeb.Text))
                {
                    SPSecurity.RunWithElevatedPrivileges(new SPSecurity.CodeToRunElevated(delegate
                    {

                        SPWeb spwRoot = SPContext.Current.Site.RootWeb;
                        ipi.MCC.Global.WebSettings wsCurrent = new ipi.MCC.Global.WebSettings(spwRoot);
                        SPWeb spwForeign = new SPSite(txtMasterWeb.Text).RootWeb;

                        if (spwRoot.ID != spwForeign.ID)
                        {
                            SPList splTreeList = null;
                            foreach (SPList splCurrent in spwForeign.Lists)
                            {
                                if (splCurrent.Title == ipi.MCC.Global.Functions.TreeList_Title)
                                {
                                    splTreeList = splCurrent;
                                }
                            }

                            if (splTreeList != null)
                            {
                                spwForeign.AllowUnsafeUpdates = true;
                                ipi.MCC.Global.WebSettings wsForeign = new ipi.MCC.Global.WebSettings(spwForeign);
                                if (!string.IsNullOrEmpty(wsForeign.MasterWebURL))
                                {
                                    throw (new UserHandlingException(Resources.Resources.MCCAdministrationPage_validMasterWeb_MasterAlreadySet));
                                }
                                else
                                {
                                    wsForeign.IsReferenceSet = true;
                                    wsForeign.Update();
                                    spwForeign.AllowUnsafeUpdates = false;

                                    spwRoot.AllowUnsafeUpdates = true;
                                    wsCurrent.MasterWebURL = spwForeign.Site.Url;
                                    wsCurrent.Update();
                                    spwRoot.AllowUnsafeUpdates = false;

                                    pnlMasterWeb.Visible = false;
                                    pnlTree.Visible = false;
                                    pnlTreeNav.Visible = false;
                                    pnlSitesTree.Visible = true;

                                    sscCurrentWeb.SelectAction = TreeNodeSelectAction.Expand;
                                    sscCurrentWeb.ShowCheckBoxes = TreeNodeTypes.Leaf;
                                    sscCurrentWeb.CheckedItems = wsCurrent.SitesToSearch;
                                    sscCurrentWeb.FillTree();

                                    ipi.MCC.Global.HandleCache.ClearSiteCache(this.Page, SPContext.Current.Site);
                                }
                            }
                            else
                            {
                                throw (new UserHandlingException(Resources.Resources.MCCAdministrationPage_validMasterWeb_ListNotFound));
                            }
                        }
                        else
                        {
                            throw (new UserHandlingException(Resources.Resources.MCCAdministrationPage_validMasterWeb_WebEquil));
                        }

                    }));
                }
                else
                {
                    throw (new UserHandlingException(Resources.Resources.MCCAdministrationPage_validMasterWeb_MustSet));
                }
            }
            catch (UriFormatException)
            {
                validMasterWeb.ErrorMessage = Exceptions.HandleException(new UserHandlingException(Resources.Resources.MCCAdministrationPage_validMasterWeb_UriFormatException), this.GetType(), MethodBase.GetCurrentMethod(), LoggingType.Exception);
                validMasterWeb.IsValid = false;
            }
            catch (Exception exc)
            {
                validMasterWeb.ErrorMessage = Exceptions.HandleException(exc, this.GetType(), MethodBase.GetCurrentMethod(), LoggingType.Exception);
                validMasterWeb.IsValid = false;
            }
        }

        protected void btnClearCache_Click(object sender, EventArgs e)
        {
            try
            {
                ipi.MCC.Global.HandleCache.ClearSiteCache(this.Page, SPContext.Current.Site);
            }
            catch (Exception exc)
            {
                validGlobal.ErrorMessage = Exceptions.HandleException(exc, this.GetType(), MethodBase.GetCurrentMethod(), LoggingType.Exception);
                validGlobal.IsValid = false;
            }
            
        }

        protected void TreeNodeSelected(TreeNode CurrentNode)
        {
            try
            {
                SPSite spsCurrent = SPContext.Current.Site;
                WebSettings wsCurrent = new WebSettings(spsCurrent);

                using (SPSite spsRoot = new SPSite(!string.IsNullOrEmpty(wsCurrent.MasterWebURL) ? wsCurrent.MasterWebURL : spsCurrent.Url))
                {
                    SPWeb spwRoot = spsRoot.RootWeb;
                    SPList splNodes = Functions.GetTreeList(spwRoot);
                    nhTreeNav.SelectNode(splNodes, CurrentNode);
                }                               
            }
            catch (Exception exc)
            {
                validGlobal.ErrorMessage = Exceptions.HandleException(exc, this.GetType(), MethodBase.GetCurrentMethod(), LoggingType.Exception);
                validGlobal.IsValid = false;
            }
            
        }

        protected void NaviNodeSelected(int iNodeID)
        {
            try
            {
                dtNavigate.SelectNode(iNodeID);
            }
            catch (Exception exc)
            {
                validGlobal.ErrorMessage = Exceptions.HandleException(exc, this.GetType(), MethodBase.GetCurrentMethod(), LoggingType.Exception);
                validGlobal.IsValid = false;
            }
            
        }

        protected void TreeStructureChanged(TreeStructureChangedTypes tscEvent, int iNodeID)
        {
            try
            {
                dtNavigate.TreeStructureChanged(tscEvent, iNodeID);
            }
            catch (Exception exc)
            {
                validGlobal.ErrorMessage = Exceptions.HandleException(exc, this.GetType(), MethodBase.GetCurrentMethod(), LoggingType.Exception);
                validGlobal.IsValid = false;
            }
            
        }

        protected void BtnSubmit_Click(object sender, EventArgs e)
        {
            ipi.MCC.Global.WebSettings wsMain = new ipi.MCC.Global.WebSettings(SPContext.Current.Site.RootWeb);
            wsMain.SitesToSearch = this.sscCurrentWeb.CheckedItems;
            wsMain.Update();
            
            Response.Redirect(SPContext.Current.Site.Url + "/_layouts/settings.aspx");
        }

        protected void BtnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(SPContext.Current.Site.Url + "/_layouts/settings.aspx");
        }
    }
}
